import ChannelBase from "../base/ChannelBase";
import ChannelData from "../data/ChannelData";
import ChannelManager from "../manager/ChannelManager";

export default class TTChannel extends ChannelBase {

    private isToutiao: boolean;
    private isDev: boolean;

    /**
     * 初始化渠道
     */
    protected InitChannel() {
        this.is_has_ad = true;
        this.is_has_share = true;
        this.is_has_recorder = true;

        this.isToutiao = tt.getSystemInfoSync().appName == "Toutiao";
        this.isDev = tt.getSystemInfoSync().appName == "devtools";

        if (this.is_has_ad) {
            this.CreateVideo();
            this.InitRecorder();
        }

        this.banner_height = 165;

        //菜单栏分享
        tt.showShareMenu({ withShareTicket: false });
        tt.onShareAppMessage(function (res) {
            return {
                title: ChannelData.share_title,
            };
        });
    }

    //#region 广告相关
    /**
     * 创建插屏广告
     */
    public CreatePage() {

    }
    /**
     * 展示插屏广告
     */
    public ShowPage(on_successed: Function, on_failed: Function) {
        // 插屏广告仅今日头条安卓客户端支持
        if (this.isToutiao) {
            const interstitialAd = tt.createInterstitialAd({
                adUnitId: this.page_id_list[0]
            });
            interstitialAd
                .load()
                .then(() => {
                    interstitialAd.show();
                })
                .catch(err => {
                    console.log(err);
                });
        }
    }

    /**
     * 创建视频广告
     */
    public CreateVideo() {
        if (!this.isDev) {
            this.video_obj = tt.createRewardedVideoAd({
                adUnitId: this.video_id_list[0]
            });
            this.video_obj.load();
            this.video_obj.onClose(res => {
                if (res.isEnded) {
                    if (this.video_successed != null && this.video_successed != undefined) {
                        this.video_successed();
                    }
                } else {
                    if (this.video_failed != null && this.video_failed != undefined) {
                        this.video_failed();
                    }
                }
            });
            this.video_obj.onError(res => {
                if (this.video_failed != null && this.video_failed != undefined) {
                    this.video_failed();
                }
                console.error(res.errMsg + '----' + res.errCode);
            });
        }
    }
    /**
     * 展示视频广告
     */
    public ShowVideo(on_successed: Function, on_failed: Function) {
        if (!this.isDev) {
            this.video_successed = on_successed;
            this.video_failed = on_failed;
            this.video_obj.show().catch(err => {
                this.video_failed();
            });
        } else {
            if (on_failed) on_failed();
        }
    }

    /**
     * 展示banner广告
     */
    public ShowBanner(on_successed: Function, on_failed: Function) {
        if (!this.isDev) {
            let sysInfo = tt.getSystemInfoSync();
            let width = sysInfo.windowWidth;
            let height = sysInfo.windowHeight;

            this.banner_obj = tt.createBannerAd({
                adUnitId: this.banner_id_list[0],
                style: {
                    width: 208
                }
            });

            this.banner_obj.onLoad(() => {
                this.banner_obj.show();
            });

            this.banner_obj.onError(res => {
                console.error(res.errMsg + '----' + res.errCode);
                if (on_failed) on_failed();
            });

            let self = this;
            this.banner_obj.style.top = 3000;
            this.banner_obj.style.left = 3000;

            this.banner_obj.onResize(size => {
                self.banner_obj.style.top = height - size.height;
                self.banner_obj.style.left = (width - size.width) / 2;
                self.banner_height = size.height + 10;
                if (on_successed) on_successed();
            });
        }
    }
    /**
     * 隐藏banner广告
     */
    public HideBanner() {
        if (this.banner_obj != null && this.banner_obj != undefined) {
            this.banner_obj.destroy();
            this.banner_obj = null;
        }
    }

    /**
     * 创建盒子广告
     */
    public CreateBox() { }
    /**
     * 显示盒子广告
     */
    public ShowBox() { }
    /**
     * 隐藏盒子广告
     */
    public HideBox() { }

    /**
     * 创建积木广告
     */
    public CreateJuggle() { }
    /**
     * 显示积木广告
     */
    public ShowJuggle() { }
    /**
     * 隐藏积木广告
     */
    public HideJuggle() { }

    /**
     * 创建原生广告
     */
    public CreateNative() { }
    /**
    * 展示原生广告
    */
    public ShowNative(on_successed: Function, on_failed: Function) { }
    /**
    * 隐藏原生广告
    */
    public HideNative() { }
    //#endregion 广告相关

    //#region 分享/录屏相关 
    /**
     * 分享游戏
     */
    public ShareGame() {
        tt.shareAppMessage({
            desc: ChannelData.share_title,
            imageUrl: ChannelData.share_image_url,
            query: "",
            success() {
                console.log("分享成功");
            },
            fail(e) {
                console.log("分享失败");
            },
        })
    }

    private recorder = null;
    private on_record_stop: Function = null;
    /**
     * 初始化录屏
     */
    private InitRecorder() {
        this.recorder = tt.getGameRecorderManager();

        this.recorder.onStop(res => {
            console.log(res);
            if (this.GetCurrentTimestamp(true) - ChannelData.record_start_time >= 4000) {
                ChannelData.record_path = res.videoPath;
            }
            ChannelData.is_recording = false;
            if (this.on_record_stop) this.on_record_stop();
        });

        this.recorder.onStart(res => {
            ChannelData.is_recording = true;
            ChannelData.record_start_time = this.GetCurrentTimestamp(true);
        });

        this.recorder.onError(res => {
            console.log("------>录屏时发生错误<------\n" + res);
            ChannelData.is_recording = false;
        });
    }

    /**
     * 开始录屏
     */
    public StartRecord() {
        if (!ChannelData.is_recording && this.recorder) {
            ChannelData.is_recording = true;
            this.recorder.start({
                duration: 300
            });
        } else if (!this.recorder) {
            this.InitRecorder();
            ChannelData.is_recording = true;
            this.recorder.start({
                duration: 300
            });
        }
    }

    /**
     * 停止录屏
     */
    public StopRecord(on_stop: Function) {
        if (this.recorder && ChannelData.is_recording) {
            ChannelData.is_recording = false;
            this.recorder.stop();
            this.on_record_stop = on_stop;
        }
    }
    
    /**
     * 分享录屏
     */
    public ShareRecord(on_successed: Function, on_failed: Function) {
        if (ChannelData.record_path) {
            tt.shareAppMessage({
                channel: "video",
                title: "视频分享",
                desc: ChannelData.share_title,
                imageUrl: "",
                templateId: "", // 替换成通过审核的分享ID
                query: "",
                extra: {
                    videoPath: ChannelData.record_path,
                    videoTopics: [ChannelData.record_topics_1, ChannelData.record_topics_2],
                    video_title: ChannelData.share_title, //生成的默认内容
                },
                success() {
                    ChannelData.record_path = null;
                    ChannelData.is_recording = false;
                    ChannelManager.GetInstance().ShowToast("分享视频成功！");
                    if (on_successed) on_successed();
                },
                fail(err) {
                    ChannelManager.GetInstance().ShowToast("分享视频失败！");
                    console.log(err);
                    if (on_failed) on_failed();
                },
            });
        } else {
            ChannelManager.GetInstance().ShowToast("暂无可分享视频");
        }
    }
    //#endregion 分享/录屏相关

    /*
     * 获取设备信息
     */
    public GetSystemInfo() {return tt.getSystemInfo({});}

    /*
     * 短震动
     */
    public VibrateShort() { tt.vibrateShort({}); }
    
    /*
     * 长震动
     */
    public VibrateLong() { tt.vibrateLong({}); }

    /**
     * 打开另一个小程序
     * @param target 目标小程序appid
     * @param path 打开的页面路径
     * @param extraData 需要传递给目标小程序的数据
     * @param ON_SUCCESS 成功回调,返回参数res
     * @param ON_FAILED 失败回调,返回参数res
     * @param is_developer envVersion 的合法值是否为 develop(开发版)
     */
    public NavigateToMiniProgram(target: string, path: string, extraData: object, ON_SUCCESS: Function, ON_FAILED: Function, is_developer = false) {

    }

    //#region 生命周期
    public OnShow(callback: Function) {
        tt.onShow(callback);
    }
    public OnHide(callback: Function) {
        tt.onHide(callback);
    }
    public OffShow(callback: Function) {
        tt.offShow(callback);
    }
    public OffHide(callback: Function) {
        tt.offHide(callback);
    }
    public GetLaunchOptionsSync(): any {
        return tt.getLaunchOptionsSync();
    }
    public GetEnterOptionsSync(): any {
        return tt.getEnterOptionsSync();
    }
    public ExitMiniProgram(on_successed: Function, on_failed: Function, on_complete: Function) {
        tt.exitMiniProgram(on_successed, on_failed, on_complete);
    }
    //#endregion 生命周期
}
